<template>
  <el-dialog
    class="basic-dialog"
    :model-value="visible"
    :title="dialogTitle"
    :width="500"
    :close-on-click-modal="!loading"
    :close-on-press-escape="!loading"
    :show-close="!loading"
    @closed="handleClosed"
    @open="handleDialogOpen"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-position="top"
      require-asterisk-position="right"
    >
      <el-form-item prop="type" class="hide-star">
        <template #label>
          <basic-form-item-tooltip
            star
            title="记录类型"
            content="指解析记录的用途，例如：网站、邮箱"
          />
        </template>
        <el-select
          v-model="formData.type"
          class="w-full"
          placeholder="选择记录类型"
        >
          <el-option
            v-for="item in logOpts"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="name">
        <template #label>
          <basic-form-item-tooltip
            title="主机记录"
            content="指域名前缀，例如：www"
          />
        </template>
        <div class="flex items-center w-full">
          <el-input
            v-model="formData.name"
            class="append-domain"
            placeholder="请填写域名前缀"
          >
            <template #append>
              <host-tips :text="`.${domain.name}`"></host-tips>
            </template>
          </el-input>
        </div>
      </el-form-item>
      <!--
      <el-form-item class="hide-star">
        <template #label>
          <basic-form-item-tooltip
            star
            title="解析请求来源"
            content="指域名访问者所在的地区或使用的运营商网络"
          />
        </template>
        <section class="flex items-center gap-x-[10px] w-full">
          <el-select
            v-model="group_name"
            class="w-[140px]"
            @change="handleChangeGroup"
          >
            <el-option
              v-for="item in groups"
              :key="item.label"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-form-item class="flex-1 hide-star" prop="line">
            <el-select
              v-model="formData.line"
              filterable
              :disabled="group_name === 'default'"
              class="flex-1"
              placeholder="请选择"
            >
              <el-option
                v-for="item in getLinesByGroupName"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </section>
      </el-form-item>
      -->
      <el-form-item prop="value">
        <template #label>
          <basic-form-item-tooltip title="记录值" content="" />
        </template>
        <el-input
          v-model="formData.value"
          :placeholder="getValuePlaceHolder(formData.type!)"
        ></el-input>
      </el-form-item>
      <el-form-item
        v-if="formData.type === 'MX'"
        label="MX优先级"
        class="mb-8"
        prop="priority"
      >
        <el-input-number
          v-model="formData.priority"
          :precision="0"
          :min="1"
          :max="50"
          controls-position="right"
          class="w-full"
          placeholder="请输入MX优先级"
        />
      </el-form-item>
      <el-form-item prop="ttl" class="hide-star">
        <template #label>
          <basic-form-item-tooltip
            star
            title="TTL"
            content="指解析结果在Local DNS中的缓存时间"
          />
        </template>
        <el-select v-model="formData.ttl" class="w-full">
          <el-option
            v-for="item in ttlOpts"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button :loading="loading" type="primary" @click="handleSubmit">
        确定
      </el-button>
      <el-button :loading="loading" @click="emit('update:visible', false)"
        >取消</el-button
      >
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormItemRule } from 'element-plus'

import type { CommonParams } from '@/apis/model/_utils'
import type { DomainRecordModel } from '@/apis/model/domain'
import { HostTips } from '@/components/business'
// import { groups, lines } from '@/config'
import {
  E_RECORD_TYPE,
  getValuePlaceHolder,
  logOpts,
  ttlOpts
} from '@/config/enums/record'
import ToastUtils from '@/utils/toast'

import type { Domain } from '../types'

interface IProps {
  visible: boolean
  loading?: boolean
  record?: DomainRecordModel
}

interface IEmits {
  (event: 'update:visible', value: boolean): void
  (event: 'update:loading', value: boolean): void
  (event: 'reload'): void
}

type IFormData = CommonParams<'/v1/rr', 'post'>

const emit = defineEmits<IEmits>()
const props = defineProps<IProps>()

const formRef = ref<FormInstance>()

// 操作的域名
const domain = inject<Domain>('domain') as Domain

// dialog title
const dialogTitle = computed(() => {
  return props.record ? '修改记录' : '添加记录'
})

// const group_name = ref('default')
// 表单数据
const formData = reactive<IFormData>({
  domain_id: domain.id,
  type: E_RECORD_TYPE.A,
  name: '',
  value: '',
  priority: 10,
  ttl: 600
  // line: ''
})

// const getLinesByGroupName = computed(() => {
//   return lines.filter(item => item.group_name === group_name.value)
// })
// 表单验证规则
const formRules = reactive<{ [key in keyof IFormData]: FormItemRule[] }>({
  type: [{ required: true, message: '请选择记录类型', trigger: 'change' }],
  name: [
    {
      validator: hostValidate(() => domain.name),
      trigger: 'blur'
    }
  ],
  value: [
    { required: true, message: '请输入记录值', trigger: 'blur' },
    {
      trigger: 'blur',
      // 服务器IP、CDN域名、邮件服务域名
      validator: logValueValidate(() => formData.type!)
    }
  ],
  ttl: [{ required: true, message: '请选择TTL', trigger: 'change' }]
  // line: [{ required: true, message: '请选择线路', trigger: 'change' }]
})
// const handleChangeGroup = () => {
//   if (group_name.value === 'default') return (formData.line = 'default')
//   formData.line = ''
// }
/**
 * 保存方法
 */
const handleSubmit = async () => {
  await formRef.value?.validate()
  emit('update:loading', true)
  try {
    if (props.record?.id) {
      await putDomainRecordApi({
        id: props.record.id,
        ...formData,
        name: formData.name || '@',
        priority: formData.type === 'MX' ? formData.priority : undefined
      })
    } else {
      const data = {
        ...formData,
        name: formData.name || '@',
        priority: formData.type === 'MX' ? formData.priority : undefined
      }
      await postDomainRecordApi(data)
    }
    ToastUtils.success(props.record?.id ? '修改成功' : '创建成功')
    handleClosed()
    emit('reload')
  } finally {
    emit('update:loading', false)
  }
}
/**
 * dialog 打开事件
 */
const handleDialogOpen = () => {
  if (props.record) {
    formData.type = props.record.type
    formData.name = props.record.name
    formData.value = props.record.value
    formData.ttl = props.record.ttl
    formData.priority = props.record.priority ?? 10
    // group_name.value =
    //   lines.find(v => v.value === props.record?.line)?.group_name ?? 'default'
    // formData.line = props.record.line
  }
  // else {
  //   formData.line = 'default'
  // }
}

/**
 * dialog 关闭前事件
 */
const handleClosed = () => {
  emit('update:visible', false)
  emit('update:loading', false)
  // group_name.value = 'default'
  formRef.value?.resetFields()
}
</script>

<style scoped lang="scss">
:deep(.el-input) {
  input {
    &::placeholder {
      @apply text-[12px];
    }
  }
}
</style>
